package com.spring.arch.common.validator;

import com.spring.arch.common.validator.constraints.NotInjured;
import com.spring.arch.common.validator.constraints.NotInjured;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.text.StringEscapeUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 有害字符验证类
 * @author Frank
 * @version 1.0.0.1
 */
public class NotInjuredValidator implements ConstraintValidator<NotInjured, String> {

	private static String[] defaultInjureArray = new String[] {" ", "\t", "\r", "\n"};
	private String[] injureArray;
	
	public static void initDefault(String defaultStr) {
		if (defaultStr != null) {
			defaultInjureArray = StringEscapeUtils.unescapeJava(defaultStr).split(",");
		}
	}
	
	@Override
	public void initialize(NotInjured annotation) {
		injureArray = annotation.value();
		if (ArrayUtils.isEmpty(injureArray)) {
			injureArray = defaultInjureArray;
		}
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		boolean ret = true;
		if (value != null) {
			for (String injure : injureArray) {
				ret &= !value.contains(injure);
			}
		}
		return ret;
	}
}
